using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Questions;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Questions
{
    /// <summary>
    /// 新增常见问题命令处理
    /// </summary>
    public class AddNewProblemCommandHandler : IRequestHandler<AddNewProblemCommand, ApiResult<int>>
    {
        /// <summary>
        /// 问题仓储
        /// </summary>
        private readonly IBaseRepository<ProblemManagementModel> _problemRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<AddNewProblemCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="problemRepository">问题仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public AddNewProblemCommandHandler(
            IBaseRepository<ProblemManagementModel> problemRepository, 
            IMapper mapper, 
            ILogger<AddNewProblemCommandHandler> logger)
        {
            _problemRepository = problemRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增常见问题命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddNewProblemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证标题是否已存在
                var existingProblem = _problemRepository.GetAll()
                    .Where(x => x.ProblemTitle == request.ProblemTitle);
                
                // 如果已存在，返回错误
                if (existingProblem.Any())
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "常见问题标题已存在！",
                        data = 0
                    };
                }

                _logger.LogInformation("开始处理常见问题新增命令，标题：{Title}", request.ProblemTitle);
                
                // 创建问题实体
                var problemEntity = _mapper.Map<ProblemManagementModel>(request);
                problemEntity.CreatedTime = DateTime.Now;
                problemEntity.UpdatedTime = DateTime.Now;
                problemEntity.CreatedBy = 1; // 这里应该从当前用户上下文获取
                problemEntity.UpdatedBy = 0;
                
                _logger.LogDebug("常见问题实体映射完成，实体信息：{@Entity}", problemEntity);

                // 保存到数据库
                _logger.LogInformation("开始保存常见问题到数据库");
                var result = await _problemRepository.AddAsync(problemEntity);
                _logger.LogInformation("数据库保存完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("常见问题新增成功，ID：{Id}", problemEntity.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "常见问题新增成功",
                        data = problemEntity.Id
                    };
                }
                else
                {
                    _logger.LogWarning("常见问题新增失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "常见问题新增失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "常见问题新增过程中发生异常，标题：{Title}", request.ProblemTitle);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"常见问题新增异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}